package com.wh.base.sys.user.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wh.base.sys.role.entity.Role;
import com.wh.base.sys.role.service.RoleService;
import com.wh.base.sys.user.entity.User;
import com.wh.base.sys.user.mapper.UserMapper;
import com.wh.base.sys.user.service.UserService;

import cn.dev33.satoken.stp.StpUtil;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author WangHong
 * @since 2022-03-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
	
	@Autowired
	private RoleService roleService;
	
	@Override
	public Map<String, String> simpleUser(User user) {
		Map<String, String> u = new HashMap<>();
		u.put("username", user.getUsername());
		u.put("phone", user.getPhone());
		u.put("realName", user.getRealName());
		return u;
	}

	@Override
	public Set<String> getAuthSignListByUserId(long userId) {
		List<Role> roleList = roleService.findRoleByUserId(userId);
		Set<String> authSignSet = new HashSet<>();
		for(Role role : roleList) {
			List<String> authSignList = roleService.findAuthSignByRoleId(role.getId());
			if(authSignList != null) {
				authSignSet.addAll(authSignList);
			}
		}
		return authSignSet;
	}

	@Override
	public List<String> getRoleListByUserId(long userId) {
		return roleService.findRoleFlagByUserId(userId);
	}

	@Override
	public User getUser() {
		long userId = StpUtil.getLoginIdAsLong();
		User user = getById(userId);
		return user;
	}

	@Override
	public User handleRoleList(User user) {
		if(user != null && user.getId() != null && user.getId() > 0L) {
			user.setRoleList(roleService.findRoleByUserId(user.getId()));
			user.setPassword("");
		}
		return user;
	}

	@Override
	public Page handlePageRoleList(Page page) {
		page.setRecords(handleListRoleList(page.getRecords())) ;
		return page;
	}

	@Override
	public List<User> handleListRoleList(List<User> userList) {
		if(userList != null && userList.size() > 0) {
			for(User u : userList) {
				handleRoleList(u);
			}
		}
		return userList;
	}

	@Override
	public Map<String, String> getAuthSignMapByUserId(long userId) {
		List<Role> roleList = roleService.findRoleByUserId(userId);
		Set<String> authSignSet = new HashSet<>();
		for(Role role : roleList) {
			List<String> authSignList = roleService.findAuthSignByRoleId(role.getId());
			if(authSignList != null) {
				authSignSet.addAll(authSignList);
			}
		}
		Map<String, String> map = new HashMap<>();
		for(String authSign : authSignSet) {
			map.put(authSign.replace(":", "_"), authSign);
		}
		return map;
	}

}
